#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import json
import requests
from requests.exceptions import Timeout

import chardet

from http.server import BaseHTTPRequestHandler
from urllib.parse import urlparse, unquote, parse_qs

6uhghkllimport data.config as CONFIG 
from mods.spider import Spider 


class Server(BaseHTTPRequestHandler):
    spider = Spider()
    # 返回数据
    def render(self,status,html,content_type='text/html; charset=UTF-8'):
        self.send_response(status)
        self.send_header('Content-type', content_type)
        self.end_headers()
        if content_type == 'text/html; charset=UTF-8':
            html = html.encode('utf-8')
        self.wfile.write(html)
        
    # get请求 
    def do_GET(self):
        # 解析请求的URL，获取文件名
        pp = self.path
        if self.path == '/':
            pp = "/index.html"
        
        parsed_path = urlparse(pp)
        query_string = parsed_path.query
        query_params = parse_qs(query_string)
        pp = parsed_path.path
        methods = {
            "/api/getconfig" : "getconfig",
            "/api/addconfig" : "addconfig",
        }
        if pp in methods:
            method = getattr(self, methods[pp])
            method(*[{"data":query_params}])
            return True
        # 静态文件加载 包括html文件
        file_path = unquote(parsed_path.path.strip('/'))
        if file_path:
            # 构建完整的文件路径
            full_file_path = os.path.join(CONFIG.html_path, file_path)
            # 检查文件是否存在和可读
            if os.path.exists(full_file_path) and os.access(full_file_path, os.R_OK):
                # 根据文件扩展名设置Content-Type
                ext = os.path.splitext(full_file_path)[1]
                content_type = {
                    '.html': 'text/html',
                    '.css': 'text/css',
                    '.js': 'application/javascript',
                    '.jpg': 'image/jpeg',
                    '.png': 'image/png',
                    '.gif': 'image/gif',
                    '.svg': 'image/svg+xml'
                }.get(ext, 'application/octet-stream')
                # 打开文件并发送HTTP响应
                with open(full_file_path, 'rb') as file:
                    self.render(200,file.read(),content_type)
            else:
                # 如果文件不存在，发送404错误
                self.render(404,"404 Not Found: The file you requested does not exist.")
        else:
            # 如果路径不存在，返回404错误
            self.render(404,"404 Not Found: The file you requested does not exist.")

    # post请求      
    def do_POST(self):
        #try:
        
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        post_data = parse_qs(post_data.decode('utf-8'))
        parsed_data = post_data['data'][0]
        parsed_data = json.loads(parsed_data)
        parsed_path = urlparse(self.path).path


        methods = {
            '/api/paseurl':"paseurl",
            '/api/listTest':"listTest",
        }
        if parsed_path in methods:
            # 使用getattr获取方法对象
            method = getattr(self, methods[parsed_path])
    
            if method:
            # 调用方法并传递参数
                method(*[parsed_path,parsed_data])
                return True

        txt = json.dumps(parsed_data,ensure_ascii=False,indent=4, sort_keys=True)
        self.render(200,txt)
        #except Exception as e:
        
          #  self.render(200,f"Caught a different exception: {e}")


    # 网站请求测试
    def paseurl(self,parsed_path,data):
        url = data['url']
        data = self.spider.testurl(url)
        self.render(200,data['data'])
                
    def listTest(self,parsed_path,data):
        url = self.spider.getListData(data,100)
        self.render(200,url)

    def getlog(self,parsed_path,data):
        pass

    def getconfig(self, query_params):
        datadir = CONFIG.path + "/data/data"
        entries = os.listdir(datadir)
        directories = [entry for entry in entries if os.path.isdir(os.path.join(datadir, entry))]
        self.render(200,json.dumps(directories))

    def addconfig(self, query_params):
        data = self.spider.addconfig()
        self.render(200,data)
